from retinaface_detector import RetinaFaceDetector
from sface_feature_extractor import sFaceFeatureExtractor
import numpy as np
from numpy.linalg import norm

class FaceDetFeature():
    def __init__(self):
        # 初始化人脸检测器
        self.face_detector = RetinaFaceDetector()  # target=None
        # 初始化特征提取器
        self.feature_extractor = sFaceFeatureExtractor()  #target=None
    
    def get_info(self, img):
        coords = []
        features = []
        faces  = self.face_detector.detect(img, score_threshold=0.5, nms_threshold=0.5)
        if len(faces ) == 0:
            print("未检测到人脸")
        else:
            # 提取人脸坐标
            for face in faces:
                x1, y1, x2, y2 = map(int, face[:4])  # 取第一个人脸的坐标
                score = face[4]
                coords.append([x1, y1, x2, y2, score])
            # 提取人脸特征
            features = self.feature_extractor.extract(img, faces)
        return coords, features
        
    def compare_features(self, feature1, feature2):
        """计算余弦相似度判断是否为同一人"""
        cos_sim = np.dot(feature1, feature2) / (norm(feature1) * norm(feature2))
        print(cos_sim)
        return cos_sim
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        # 退出with语句时执行，自动释放资源
        self.face_detector.release()
        self.feature_extractor.release()
        print("资源已自动关闭")
        return False  # 不抑制异常，让其正常抛出
